package com.qmyx.supply.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qmyx.supply.admin.annotation.oplog.annotation.OperationLog;
import com.ytjj.qmyx.supplychain.common.constants.SysLogConstants;
import com.ytjj.qmyx.supplychain.common.model.request.ProductReviewsAddRequest;
import com.ytjj.qmyx.supplychain.common.model.response.Api99Response;
import com.qmyx.supply.admin.utils.Api99Util;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.model.request.ProductRequest;
import com.ytjj.qmyx.supplychain.common.model.request.UpdateSkuRequest;
import com.ytjj.qmyx.supplychain.common.model.response.CebCountryResponse;
import com.ytjj.qmyx.supplychain.common.model.response.CebUnitResponse;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.CebCountryMapper;
import com.ytjj.qmyx.supplychain.mapper.CebUnitMapper;
import com.ytjj.qmyx.supplychain.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 供应商商品控制器
 *
 * 
 * 
 **/
@RestController
@RequestMapping("/product")
@Slf4j
@RefreshScope
public class ProductController {
    @Resource
    private ProductService productService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private BankerProductSpecService bankerProductSpecService;
    @Autowired
    private ApiDataInfoService apiDataInfoService;
    @Autowired
    private BankerService bankerService;
    @Resource
    private CebCountryMapper cebCountryMapper;
    @Resource
    private CebUnitMapper cebUnitMapper;

    @Value("${wms.bankerIds:}")
    private String wmsBankerIds;//接WMS系统供应商id


    @PostMapping("/addAndUpdate")
    @OperationLog(optModule = "商品", optType = SysLogConstants.OPERATION_UPDATE, desc = "修改商品")
    public CommonResult addAndUpdate (@RequestBody ProductRequest productRequest) {
        productService.addAndUpdate(productRequest);
        return CommonResult.success();
    }


    @GetMapping("/getProductInfo/{productId}")
    public CommonResult getProductInfo(@PathVariable Integer productId) {
        return CommonResult.success(productService.getProductInfo(productId));
    }

    @GetMapping("getCategory")
    public CommonResult getCategory(@RequestParam (required = false,defaultValue = "0") Integer parentId) {
        return CommonResult.success(productCategoryService.getList(parentId));
    }

    /**
     * 根据标题查询分类
     * @param title
     * @return
     */
    @GetMapping("/queryCategory")
    public CommonResult queryCategory(@RequestParam("title") String title) {
        return CommonResult.success(productService.queryCategoryListByTitle(title));
    }

    @GetMapping("/getTopCategory")
    public CommonResult getTopCategory() {
        return CommonResult.success(productCategoryService.getList(0));
    }

    @PostMapping("/updateProductSpec")
    public CommonResult updateProductSpec(@RequestBody UpdateSkuRequest updateSkuRequest){
        log.info("===updateProductSpec==={}", updateSkuRequest);
        bankerProductSpecService.updateProductSpec(updateSkuRequest);
        return CommonResult.success();
    }

    /**
     * 获取99API数据
     * @param url 商品详情url
     * @return
     */
    @GetMapping("/getThreeProductInfo")
    public CommonResult getThreeProductInfo(@RequestParam String url) {
        log.info("===getThreeProductInfo==={}", url);
        Integer domain = Api99Util.getDomain(url);
        String itemId = Api99Util.getItemIdByUrl(url, domain);
        String redisKey = "99api:" + itemId + ":" + domain;
        String redisValue = redisService.get(redisKey);
        Api99Response response = new Api99Response();
        if (StringUtils.isEmpty(redisValue)) {
            response = Api99Util.send(itemId, domain);
            response.setRequestUrl(url);
            try {
                apiDataInfoService.save99APIData(response);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("===save 99api is error==={}", e);
            }
            redisService.set(redisKey, JSONObject.toJSONString(response));
            redisService.expire(redisKey, 2 * 24 * 60 * 60);
        }else {
            response = JSON.parseObject(redisValue, Api99Response.class);
        }
        response.setInfoList(null == response.getDescImgList() ? new ArrayList<>() : response.getDescImgList());
        response.setBannerList(null == response.getImagesList() ? new ArrayList<>() : response.getImagesList());
        return CommonResult.success(response);
    }

    /**
     * 根据分类关键字查询所有分类
     * @param title
     * @return
     */
    @GetMapping("/getCategoryByTitle")
    public CommonResult queryCategoryListByTitle(@RequestParam("title") String title) {
        return CommonResult.success();
    }

    /**
     * 把图片转到商品表中
     */
    @GetMapping("/updateImgToTable")
    public CommonResult updateImgToTable(@RequestParam("type") String type){
        return productService.updateImgToTable(type);
    }

    /**
     * 添加商品评论
     */
    @PostMapping("/addProductReviews")
    public CommonResult addProductReviews(@RequestBody ProductReviewsAddRequest request) {
        productService.addProductReviews(request);
        return CommonResult.success();
    }

    /**
     * 获取全部国家
     * @return
     */
    @GetMapping("/findCountryAll")
    public CommonResult findCountryAll() {
        return productService.findCountryAll();
    }

    /**
     * 判断是否需要接
     */
    @GetMapping("/findWmsBankerIds")
    public CommonResult findWmsBankerIds(){
        Integer origin = 0;
        if (StringUtils.isEmpty(wmsBankerIds)) {
            return CommonResult.success(origin);
        }
        //判断是否需要发送到wms的供应商
        Integer id = bankerService.getUserInfo().getId();
        List wmsAllBankerIds = Arrays.asList(wmsBankerIds.split(","));
        if (wmsAllBankerIds.contains(id.toString())) {
            origin = 1;
        }
        return CommonResult.success(origin);
    }

    /**
     * 报关用到的国家接口-新
     * @return
     */
    @GetMapping("/new_country_list")
    public CommonResult selectContryListNew() {
        List<CebCountryResponse> list = cebCountryMapper.queryCountryList();
        List<Map<String, Object>> result = new LinkedList<>();
        list.stream().forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("code", item.getCode());
            map.put("name", item.getName());
            result.add(map);
        });
        return CommonResult.success(result);
    }

    /**
     * 报关用到的单位接口
     * @return
     */
    @GetMapping("/new_product_unit")
    public CommonResult selectProductUnitNew() {
        List<CebUnitResponse> list = cebUnitMapper.queryUnitList();
        List<Map<String, Object>> result = new LinkedList<>();
        list.stream().forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("code", item.getCode());
            map.put("name", item.getName());
            result.add(map);
        });
        return CommonResult.success(result);
    }
}
